# -*- coding: utf-8 -*-
import pygame
import random
import sys

# 初始化引擎
pygame.init()
pygame.mixer.init()

# 窗口设置
WIN_WIDTH, WIN_HEIGHT = 800, 400
screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
pygame.display.set_caption("PyDash Runner")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
SKY_BLUE = (135, 206, 235)
GROUND_GREEN = (34, 139, 34)
PLAYER_RED = (255, 0, 0)
OBSTACLE_GRAY = (128, 128, 128)

# 玩家角色类（整合网页1、网页3、网页6设计）
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((30, 50))  # 内存优化：纯色块代替图片
        self.image.fill(PLAYER_RED)
        self.rect = self.image.get_rect(midbottom=(100, WIN_HEIGHT-50))
        self.speed = pygame.math.Vector2(0, 0)
        self.gravity = 0.8
        self.jump_force = -16
        self.is_grounded = True

    def update(self, keys):
        # 水平移动（参考网页2、网页4键盘处理）
        self.speed.x = 0
        if keys[pygame.K_RIGHT]:
            self.speed.x = 7
        if keys[pygame.K_LEFT]:
            self.speed.x = -7
        
        # 跳跃机制（参考网页3重力系统）
        if keys[pygame.K_SPACE] and self.is_grounded:
            self.speed.y = self.jump_force
            self.is_grounded = False
        
        # 应用重力
        self.speed.y += self.gravity
        self.rect.y += self.speed.y
        
        # 地面检测（参考网页1碰撞检测）
        if self.rect.bottom >= WIN_HEIGHT-50:
            self.rect.bottom = WIN_HEIGHT-50
            self.speed.y = 0
            self.is_grounded = True
        
        # 横向移动
        self.rect.x += self.speed.x
        self.rect.x = pygame.math.clamp(self.rect.x, 0, WIN_WIDTH-30)

# 障碍物生成系统（参考网页1、网页5设计）
class Obstacle(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.width = random.randint(30, 60)
        self.image = pygame.Surface((self.width, 50))
        self.image.fill(OBSTACLE_GRAY)
        self.rect = self.image.get_rect(
            midbottom=(random.randint(WIN_WIDTH+100, WIN_WIDTH+300), WIN_HEIGHT-50)
        )
        self.speed = 6

    def update(self):
        self.rect.x -= self.speed
        if self.rect.right < 0:
            self.kill()

# 游戏管理器
class Game:
    def __init__(self):
        self.player = pygame.sprite.GroupSingle(Player())
        self.obstacles = pygame.sprite.Group()
        self.obstacle_timer = pygame.USEREVENT + 1
        pygame.time.set_timer(self.obstacle_timer, 1500)  # 每1.5秒生成障碍
        self.game_active = True

    def run(self):
        while True:
            # 事件处理（参考网页6事件循环）
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if self.game_active and event.type == self.obstacle_timer:
                    self.obstacles.add(Obstacle())

            # 按键检测
            keys = pygame.key.get_pressed()
            
            if self.game_active:
                # 更新游戏元素
                self.player.update(keys)
                self.obstacles.update()

                # 碰撞检测（参考网页2、网页5）
                if pygame.sprite.spritecollide(self.player.sprite, self.obstacles, False):
                    self.game_active = False

                # 画面渲染
                screen.fill(SKY_BLUE)
                pygame.draw.rect(screen, GROUND_GREEN, (0, WIN_HEIGHT-50, WIN_WIDTH, 50))
                self.player.draw(screen)
                self.obstacles.draw(screen)
            else:
                # 游戏结束画面（参考网页1 UI设计）
                screen.fill(SKY_BLUE)
                font = pygame.font.Font(None, 74)
                text = font.render('GAME OVER', True, (255, 255, 255))
                screen.blit(text, (WIN_WIDTH//2-140, WIN_HEIGHT//2-50))

            pygame.display.update()
            clock.tick(FPS)

if __name__ == "__main__":
    game = Game()
    game.run()